/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.controller;

import com.bayu.services.dao.StockDao;
import com.bayu.services.dao.TIncomingUsageDao;
import com.bayu.services.dao.TStockDao;
import com.bayu.services.entity.Stock;
import com.bayu.services.entity.TIncomingUsage;
import com.bayu.services.entity.TStock;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author submonkey
 */
@Controller
@RequestMapping("/stock-update.htm")
public class StockUpdate {
    TIncomingUsageDao tIncomingUsageDao;
    TStockDao stockDao;

    @Autowired
    private void setStockDao(TIncomingUsageDao tIncomingUsageDao) {
        this.tIncomingUsageDao = tIncomingUsageDao;
    }

    @Autowired
    private void setTStockDao(TStockDao stockDao){
      this.stockDao = stockDao;
    }


    @RequestMapping(method=RequestMethod.GET)
    public void displayForm(ModelMap map, String id) {
        List list = this.tIncomingUsageDao.getById(Integer.parseInt(id));
        map.addAttribute("data", list);
    }

    @RequestMapping(method=RequestMethod.POST)
    public String processForm(@ModelAttribute("TIncomingUsage") TIncomingUsage tIncomingUsage, BindingResult result, ModelMap map, String tanggal, HttpServletRequest request) {
        DateFormat format = new SimpleDateFormat("yy-MM-dd");
        Date tgl;
        
      
        String[] tempIdStock = tanggal.split("-");

        String idStock = tempIdStock[1]+tempIdStock[0];


        List data = this.stockDao.getById(idStock);
        TStock tStock = (TStock) data.get(0);
            

        tIncomingUsage.setIdStock(tStock);
        
       
        if (result.hasFieldErrors("tanggal")) {
            try {

                tgl = format.parse(tanggal);
                tIncomingUsage.setTanggal(tgl);
            } catch (Exception e) {
            }
        }

        String id = request.getParameter("id");
        if (id != null) {
            tIncomingUsage.setId(Integer.parseInt(id));
            this.tIncomingUsageDao.update(tIncomingUsage);
            return "redirect:view-stock-data.htm?msg=Data has been updated";
        } else {
            return "redirect:casting-update.htm";
        }
    }
}
